package com.openbravo.data.loader.dialect.PostgreSQL;

import com.openbravo.data.loader.dialect.AbstractDBDialect;
import com.openbravo.data.loader.dialect.AbstractDDLFactory;
import e.odbo.data.AbstractConfigEntry;
import e.odbo.data.model.*;
import e.odbo.data.util.StringUtils;

import java.util.List;

public class PostgreSQLDDLFactory extends AbstractDDLFactory {
    public PostgreSQLDDLFactory(AbstractDBDialect dbDialect) {
        super(dbDialect);
    }

    public static String TABLE_encoding="postgresql.ddl.encoding";

    public static class Config {
        public static AbstractConfigEntry<String> Encoding(String value) {
            return new AbstractConfigEntry(TABLE_encoding, value) {
            };
        }
    }

    @Override
    public String createDataBase(String dataBaseName) {
        return "CREATE DATABASE " + dataBaseName  +getDialectTailed();
    }


    public String generatePK(List<Column> columns){
        String ret="PRIMARY KEY (";
        for(Column column:columns)
            ret+=column.getName()+",";
        return ret.substring(0,ret.length()-2)+")";
    }

    public  String generateColumn(Column column){
        String ret=column.getName();
        ColumnType columnType=this.transformColumnTypeToDialect(column,PostgreSQL.NAME);
        ret+= " "+columnType.buildTypeString();
        if(ColumnFlag.isNotNull(column.getColumnFlag()))
            ret+=" NOT NULL ";
        if(ColumnFlag.isUnique(column.getColumnFlag()))
            ret+=" UNIQUE ";

        if(columnType.getDefaultValue()!=null)
            ret+=" DEFAULT "+columnType.getDefaultValue();
        if(ColumnFlag.isAutoGreater(column.getColumnFlag()))
            ret+=" AUTO_INCREMENT ";
        if(column.getComment()!=null)
            ret+=" COMMENT '"+column.getComment()+"'";
        return ret;
    }

    public String generateIndex(String name, String[] indexColumn){
        String ret=" KEY '"+name+"'("+ StringUtils.join(indexColumn,',')+")";
        return ret;
    }

    public String generateTableDialect(Table table){
        String ret=getConfig(TABLE_encoding)!=null?" ENCODING '"+getConfig(TABLE_encoding):"'";
        return ret;
    }


    public String generateForeign(TableForeignKey foreignKey){
        String ret="CONSTRAINT `"+foreignKey.getName()+"` FOREIGN KEY ("+StringUtils.join(foreignKey.getColumns(),',')+")";
        ret+=" REFERENCES '"+foreignKey.getRefTable()+"'("+StringUtils.join(foreignKey.getRefColumns(),',')+")";
        if(foreignKey.isCascadeFlag_del())
            ret+=" ON DELETE "+foreignKey.getCascadeFlag_del().getName()+" ";
        if(foreignKey.isCascadeFlag_update())
            ret+=" ON UPDATE "+foreignKey.getCascadeFlag_update().getName()+" ";

        return ret;
    }
}
